import { message, Modal } from 'ant-design-vue'
import { uuid } from 'g6-fn'
import { onUnmounted, ref } from 'vue'

import { useUserInfoStore } from '@/store'

// 导入环境变量
const { VITE_WS_TARGET } = import.meta.env

export type WebSocketStatus = 'SUCCESS' | 'ERROR' | 'CLOSE' | 'CONNECTING'
export interface TagChangeConfig {
  onMessage?: (e: MessageEvent) => void
  onOpen?: (e: any) => void
}

// 标签变更
export const useTagChange = (config?: TagChangeConfig) => {
  let ws: WebSocket | null = null

  const userInfoStore = useUserInfoStore()
  const userId = userInfoStore?.userInfo?.id
  const status = ref<WebSocketStatus>('CONNECTING')
  let tagChangeModal: any

  const connect = (taskId: string) => {
    // const url = `/socket/mark/mark-manage-label/${taskId}_${userId}`
    const url = `${VITE_WS_TARGET}/mark/mark-manage-label/${taskId}_${userId}`

    try {
      ws = new WebSocket(url)
    } catch (error) {
      console.log('error', error)
    }

    if (!ws) {
      message.error('WebSocket连接错误,请刷新页面重试')
      return
    }

    ws.onopen = () => {
      console.log('连接成功')
      status.value = 'SUCCESS'
    }
    ws.onmessage = e => {
      config?.onMessage && config?.onMessage(e)
      const { data } = e
      if (!data) {
        return
      }
      tagChangeModal && tagChangeModal?.destroy?.()
      tagChangeModal = Modal?.warning({
        title: '标签变更提醒',
        content: data,
        centered: true
      })
    }
    ws.onclose = () => {
      console.log('连接关闭')
      status.value = 'CLOSE'
    }
    ws.onerror = e => {
      console.log('连接错误', e)
      status.value = 'ERROR'
      message.error('WebSocket连接错误,请刷新页面重试')
    }
  }

  const send = (data: any) => {
    if (ws) {
      ws.send(JSON.stringify(data))
    }
  }

  const close = () => {
    if (ws) {
      ws.close()
    }
  }

  onUnmounted(() => {
    close()
  })

  return {
    ws,
    send,
    connect,
    close
  }
}

// 同一文本只允许一个人标注
export const useUniqueLabel = (config?: TagChangeConfig) => {
  let ws: WebSocket | null = null

  const status = ref<WebSocketStatus>('CONNECTING')
  const userInfoStore = useUserInfoStore()
  const userId = userInfoStore?.userInfo?.id
  // 是否被锁定（有用户正在编辑）
  const isLocked = ref(false)

  const connect = () => {
    // const url = `/socket/mark/mark-change-info/${uuid()}`
    const url = `${VITE_WS_TARGET}/mark/mark-change-info/${uuid()}`
    try {
      ws = new WebSocket(url)
    } catch (error) {
      console.log('error', error)
    }

    if (!ws) {
      message.error('WebSocket连接错误,请刷新页面重试')
      return
    }

    ws.onopen = e => {
      console.log('连接成功')
      status.value = 'SUCCESS'
      config?.onOpen && config?.onOpen(e)
    }
    ws.onmessage = e => {
      config?.onMessage && config?.onMessage(e)
      const { data } = e
      console.log(data, 'data')
      if (data === 'false') {
        isLocked.value = true
        message.error('分享用户正在标注此数据，暂不支持编辑')
      }
    }
    ws.onclose = () => {
      console.log('连接关闭')
      status.value = 'CLOSE'
    }
    ws.onerror = e => {
      console.log('连接错误', e)
      status.value = 'ERROR'
      message.error('WebSocket连接错误,请刷新页面重试')
    }
  }

  const send = (data: any) => {
    if (ws) {
      const params = {
        ...data,
        userId: userId
      }
      isLocked.value = false
      ws.send(JSON.stringify(params))
    }
  }

  const close = () => {
    if (ws) {
      ws.close()
    }
  }

  onUnmounted(() => {
    close()
  })

  return {
    isLocked,
    ws,
    send,
    connect,
    close
  }
}
